/**
 * Copyright 2021 Huawei Technologies Co., Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef EXECUTE_GRAPH_BUFFER_POOL_H
#define EXECUTE_GRAPH_BUFFER_POOL_H

#include <cstring>
#include <memory>
#include "definitions.h"
namespace ge {
using PoolOffset = size_t;
constexpr PoolOffset kInvalidOffset = SIZE_MAX;
class BufferPool {
 public:
  BufferPool();
  explicit BufferPool(size_t capability);

  BufferPool &operator=(BufferPool &&other) noexcept;

  // 添加一段buffer，返回添加到BufferPool的offset
  PoolOffset AddBuffer(const void *buf, size_t len);
  Status Resize(size_t new_size);
  void Reset();
  void Swap(BufferPool &other) noexcept;

  void *GetBase() const;
  size_t GetLen() const;
  size_t GetCapability() const;

  /**
   * 获取Buffer，返回的指针owner归属于BufferPool。
   * `AddBuffer`函数可能会使返回的指针失效，因此在Buffer稳定前（即不再调用`AddBuffer`添加新内容了），**不要**保存`GetBuffer`返回的指针！！
   * @param offset
   * @return
   */
  void *GetBuffer(PoolOffset offset);

 private:
  Status Expand(size_t add_len);

  size_t capability_;
  size_t len_{0};
  std::unique_ptr<uint8_t> data_;
};

}

#endif  //EXECUTE_GRAPH_BUFFER_POOL_H
